<?php

namespace app\admin\controller;

use app\admin\service\CityService;
use support\spark\model\system\SetCity;
use support\Request;
use support\spark\exception\ApiException;
use support\View;

class CityController extends Curd
{

    /**
     * 获取列表
     */
    public function index()
    {
        $pid = request()->input('pid', 0);
        $level = request()->input('level', 0);
        $where[] = ['pid', '=', $pid];
        $cityService = new CityService();
        $res = $cityService->getList($where, $level);
        if (request()->isAjax()) {
            return sparkSuccess($res);
        }
        View::assign([
            'tree' => json_encode($res['data'])
        ]);

        return view('city/index');
    }

    /**
     * 添加
     */
    public function add()
    {
        if (request()->isAjaxPost()) {

            $param = request()->post();

            $cityService = new CityService();
            $res = $cityService->addCity($param);
            return sparkSuccess($res);
        }

        return view('city/add');
    }

    /**
     * 编辑
     */
    public function edit()
    {
        if (request()->isAjaxPost()) {
            $param = request()->post();
            $cityService = new CityService();
            $res = $cityService->editCity($param);
            return sparkSuccess($res);
        }

        $id = request()->input('id');
        $setCityModel = new SetCity();
        View::assign([
            'info' => $setCityModel->getInfoByWhere([
                'id' => $id
            ])
        ]);

        return view('city/edit');
    }

    /**
     * 删除
     */
    public function del()
    {
        $id = request()->input('id');
        $setCityModel = new SetCity();
        $has = $setCityModel->where('pid', $id)->first();
        if (!empty($has)) {
            throw new  ApiException('该地区下还存在地区，不可删除', -1);
        }
        $setCityModel->delById($id);
        return sparkSuccess(dataReturn(0, '删除成功'));
    }

    /**
     * 获取所有的区域
     */
    public function area()
    {
        $cityService = new CityService();
        $res = $cityService->getAreaTree();

        return sparkSuccess($res);
    }
}